package com.mxw.account.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mxw.account.dto.AccountDTO;
import com.mxw.account.mapper.AccountMapper;
import com.mxw.account.mapper.domain.Account;
import com.mxw.account.mapper.domain.AccountEntity;
import com.mxw.account.service.AccountService;
import com.mxw.commons.errorcode.GlobalErrorCode;
import com.mxw.commons.exception.CustomException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Slf4j
@Service
public class AccountServiceImpl extends ServiceImpl<AccountMapper, Account>
    implements AccountService {
  @Autowired TestHandler testHandler;

  @Override
  public Account selectByCode(String accountCode) {
    LambdaQueryWrapper<Account> queryWrapper =
        new QueryWrapper<Account>()
            .lambda()
            .eq(StringUtils.isNotBlank(accountCode), Account::getAccountCode, accountCode);
    List<Account> accounts = this.baseMapper.selectList(queryWrapper);
    if (accounts.isEmpty()) {
      throw new CustomException(GlobalErrorCode.DATA_NOT_FOUND, "未查询到数据");
    }
    return accounts.get(0);
  }

  @Override
  @Transactional(rollbackFor = Exception.class)
  public Boolean saveAccount(AccountDTO accountDTO) {
    Account account = BeanUtil.copyProperties(accountDTO, Account.class);
    //    int i = 1/0;
    return this.save(account);
  }

  @Async
  @Override
  public Boolean asyncSaveAccount(AccountDTO accountDTO) {
    Account account = BeanUtil.copyProperties(accountDTO, Account.class);
    return this.save(account);
  }

  @Override
  public AccountEntity jpaTest(AccountDTO accountDTO) throws Exception{
    return testHandler.jpaTest(accountDTO);
  }
}
